package com.daervin.svc.iml;

import com.daervin.common.code.CodeEnum;
import com.daervin.common.dto.Result;
import com.daervin.common.dto.request.SaveReq;
import com.daervin.common.utils.URLUtil;
import com.daervin.common.utils.Md5Util;
import com.daervin.svc.IAdminService;
import com.daervin.svc.dal.IDarlingDataDao;
import com.daervin.svc.dal.model.DarlingData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by daervin on 2021/4/1
 */
@Service
public class AdminServiceImpl implements IAdminService {
    @Autowired
    private IDarlingDataDao dataDao;

    @Override
    public Result<String> saveNew(SaveReq req) {
        String md5 = Md5Util.md5(req.getOriginalUrl());
        Integer count = dataDao.selectByMd5(md5);
        if (count != null && count > 0) {
            return new Result(CodeEnum.REPEATED);
        }
        String shortKey = URLUtil.shortUrl(req.getOriginalUrl());
        DarlingData darlingData = new DarlingData();
        darlingData.setShortKey(shortKey);
        darlingData.setOriginalUrl(req.getOriginalUrl());
        darlingData.setMd5Str(md5);
        darlingData.setHitCount(req.getHitCount().longValue());
        darlingData.setDptId(req.getDptId());
        darlingData.setCreateTime(new Date());
        darlingData.setExpireTime(0L);
        dataDao.insert(darlingData);
        if (darlingData.getId() == null) {
            return new Result(CodeEnum.SYSTEM_ERROR);
        }
        return new Result(CodeEnum.SUCCESS, shortKey);
    }
}
